#!/usr/bin/env python 
# coding:utf-8
# @Time :9/11/18 14:47

from common.config_parser import ConfigParser
import threading


class FileConfigLoader(object):

    def __init__(self, file_path, log):
        self.logger = log
        self.__file_path = file_path
        self.__lock = threading.Lock()

    # 从文件中加载配置
    def load_conf(self):
        config_parser = ConfigParser(self.__file_path)
        return config_parser.get_all_session()

    # 存储配置
    def save_conf(self, **config_dict):
        try:
            self.__lock.acquire()
            with open(self.__file_path, 'w') as p_file:
                for table_name, session_dict in config_dict.items():
                    p_file.writelines("[{}]\n".format(table_name))
                    for key, value in session_dict.items():
                        if isinstance(value, list) or isinstance(value, dict) or isinstance(value, tuple):
                            self.logger.error("当前字段异常, 无法存储: value = {}".format(value))
                            continue
                        p_file.writelines("{}={}".format(key, value))

            self.logger.info("存储配置成功")
        finally:
            self.__lock.release()


